/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bblocks.auth.support.service.impl;

import com.bblocks.auth.support.service.AppUserDemoDetailsService;
import com.bblocks.enums.AppTypeEnum;
import com.bblocks.enums.CodeTypeEnum;
import com.bblocks.enums.LoginTypeEnum;
import com.bblocks.enums.SysEnum;
import com.bblocks.pojo.ComUser;
import com.bblocks.sms.service.SmsCheckCodeService;
import com.bblocks.util.R;
import com.pig4cloud.pig.admin.api.dto.UserInfo;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.stereotype.Service;

/**
 * 用户手机号详细信息
 *
 * @author Zhao
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AppDemoMobileUserDetailsServiceImpl extends AppUserDemoDetailsService {

	private final RemoteUserService remoteUserService;
	private final SmsCheckCodeService smsCheckCodeService;
	/**
	 * 用户密码登录
	 * @param phone 用户密码登录
	 * @return
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String phone) {
		log.info("appdemo 查询用户：{}",phone);
		R<UserInfo> result = remoteUserService.infoByMobileInner(phone);
		return getUserDetails(result);
	}

	@Override
	public UserDetails loadUserByUser(ComUser pigxUser) {
		return pigxUser;
	}



	@Override
	public int getOrder() {
		return 15;
	}

	/**
	 * 支持所有的 mobile 类型
	 * @param clientId 目标客户端
	 * @param grantType 授权类型
	 * @return true/false
	 */
	@Override
	public boolean support(String clientId, String grantType, AppTypeEnum apptype) {
		return  LoginTypeEnum.Sms.getName().equals(grantType) && this.appType() == apptype;
	}

	/**
	 *  验证码校验（2个方案）
	 *  1、共享redis进行操作（本处用此方案）
	 *  2、提供远程接口
	 * @param userDetails
	 * @param authentication
	 * @param messages 国际化消息
	 */
	public void check(UserDetails userDetails,
					  UsernamePasswordAuthenticationToken authentication
			, MessageSourceAccessor messages){
		log.info("appdemo 校验用户：{}",authentication.getPrincipal());
		if (authentication.getCredentials() == null) {
			throw new BadCredentialsException(messages
					.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		}
		String mobile = authentication.getPrincipal().toString();
		String code = authentication.getCredentials().toString();

		SysEnum ret = smsCheckCodeService.chkCode(mobile,code, CodeTypeEnum.CodePub,false);
		if(SysEnum.SUCCESS != ret){
			throw new OAuth2AuthenticationException(ret.getMessage());
		}
	}

}
